<template>
  <div v-show="userState.pageIndex === 3" class="login_container">
      <h3>绑定手机号</h3>
      <div class="phoneBind">
          <p v-if="userState.betaVersion">内测用户手机号绑定</p>
          <p v-if="!userState.betaVersion">用户手机号绑定</p>
      </div>
      <!-- 密码登录 -->
      
      <!-- 验证码登录 -->
      <div class="phoneLogin">
          <div class="input_row">
              <el-form class="el_form" :model="phoneData" :rules="phoneRules" ref="phoneFormRef">
                  <el-form-item label="" prop="phoneNumber">
                      <el-input 
                          type="text"
                          v-model="phoneData.phoneNumber"
                          :placeholder="userState.betaVersion?'内测用户请输入手机号码':'请输入手机号码'"
                          >
                      </el-input>
                  </el-form-item>
                  <el-form-item label="" prop="code">
                      <el-col :span="17">
                          <el-input 
                              type="text" 
                              v-model="phoneData.code"  
                              placeholder="请输入验证码"
                              ></el-input>
                      </el-col>
                      <el-col :span="7">
                          <div class="phoneCode_con">
                              <button type="button" :disabled="phoneCodeDisabled" @click="getPhoneCode">{{ getPhoneText }}</button>
                          </div>
                      </el-col>
                  </el-form-item>
                  <el-form-item label="" prop="isread" class="centered_item">
                      <div class="read_row">
                          <el-checkbox name="isread" class="read_checkbox" v-model="phoneData.isread"/> 我已经阅读并同意<a href="javascript:;">《用户协议》</a>和<a href="javascript:;">《隐私政策》</a>
                      </div>
                  </el-form-item>
                  <el-form-item>
                      <div class="to_pass_login">
                          <button type="button" class="login_btn" @click="phoneSubmitForm">
                              确定
                          </button>
                      </div>
                      <!-- 第三方授权登录 -->
                      <!-- <div class="orther_login">
                          <button type="button" @click="toWxLogin">第三方授权登录</button>
                      </div> -->
                  </el-form-item>
              </el-form>
          </div>  
      </div>
      <!-- <div class="regist_findpass">
          <p>没有账号？<a href="javascript:;" @click="toRegist">立即注册</a></p>
          <p>忘记密码？<router-link tag="a">找回密码</router-link></p>
      </div> -->
  </div>
</template>

<script setup>
import { reactive, ref, inject, toRaw, getCurrentInstance } from 'vue';
import { ElLoading, ElMessage } from 'element-plus';
import { login, sendSmsForLogin, loginBySmsCode } from '../../api/login';
import { getUserInfo } from '../../api/user';
import { useUserStore } from '../../store/user';
import { useRoute } from 'vue-router'
import config from '../../utils/config'
import axios from 'axios';

const { userState, setUsername, setToken  } = useUserStore();

const phoneFormRef = ref(null)              // 验证码登录form对象
// let logintabNum = ref(0)                    // 切换密码登录与手机验证码登录 1.密码登录， 2.手机验证码登录
let phoneCodeDisabled = ref(false)          // 倒计时读秒时禁用获取验证码按钮
let getPhoneText = ref('获取验证码')          // 倒计时显示读秒
let second = 60                             // 倒计时秒数
let timer = null                            // 倒计时setInterval
let loginLoading  = null
const route = useRoute();

const instance = getCurrentInstance();
const eventBus = instance?.proxy.$eventBus;

// phoneData.phoneNumber
let phoneData = reactive({
  phoneNumber: '',
  code: '',
  isread: false
})

const isReadValidator = (rule, value, callback) => {
  if (!value) {
      return callback('请先勾选协议')
  } else {
      callback()
  }
}


// 验证码登录校验
const phoneRules = {
  phoneNumber: [
      { required: true, message: '请输入手机号码', trigger: 'blur' },
      { pattern: /^[1][3-9][0-9]{9}$/, message: '请输入有效的手机号码', trigger: 'blur' }
  ],
  code: [
      { required: true, message: '请输入验证码', trigger: 'blur' }
  ],
  isread: [
      {validator: isReadValidator,trigger: 'change'}
  ]
}

// 获取验证码
function getPhoneCode() {
  phoneFormRef.value.validateField('phoneNumber', (valid) => {
      console.log(valid)
      // toLogin()
      if (valid) {
          phoneCodeDisabled.value = true
          second-- 
          getPhoneText.value = second+'秒后重新发送'
          timer = setInterval(() =>{
              second-- 
              getPhoneText.value = second+'秒后重新发送'
              if (second<=0) {
                  getPhoneText.value = '获取验证码'
                  second = 10
                  phoneCodeDisabled.value = false
                  clearInterval(timer)
              }
          },1000)

          sendSmsForLogin({
              phoneNumber: phoneData.phoneNumber
          }).then(res => {
              // 发送成功
          }).catch( error => {
            ElMessage({
                message: '获取验证码失败',
                type: 'error',
                duration: 5 * 1000
            })
          })

      }
  })
}



// 手机验证码登录
async function phoneSubmitForm() {

  phoneFormRef.value.validate((valid) => {
      if (valid) {
          loginLoading = ElLoading.service({
              target: document.querySelector('.login_container'),
              text: '绑定中请稍后',
              customClass: 'custom-loading',
              background: 'rgba(0, 0, 0, 0.7)',
          })

          const data = {
            wechatID: userState.uuid,
            phoneNumber: phoneData.phoneNumber,
            code: phoneData.code,
          }

          const url = config.BaseUrl + '/user/bindWechatID'
          axios({
            method:'POST',
            url,
            type: "Content-Type: application/json",
            timeout: 5000,
            data
          }).then(res => {
            console.log('手机号绑定res:', res)
            loginMethod(res)
          }).catch((error) => {

            console.error(error)
              ElMessage({
                message: '绑定失败',
                type: 'error',
                duration: 5 * 1000
            })
            // userState.pageIndex = 2
            loginLoading.close()

          })
      }
  })
}

// 统一登录方法
function loginMethod(res) {

  console.log('loginMethod-res:', res)
  const data = res.data.data
  const status = res.data.status 

  //  status: 404, msg: "用户不存在，请先注册用户！"
  //  status: 502, msg: "服务器异常，绑定微信到用户失败！"
  //  status: 200, msg: "验证通过，绑定微信到用户成功！",
  //  status: 401, msg: "验证码输入有误，绑定微信到用户失败！"
  //  status: 401, msg: "验证码为空，绑定微信到用户失败！"
  //  status: 500, msg: "服务器出现未知异常！"

  if ( status == '200' ) {
      setToken(data.token)
      userState.id = data.id
      userState.isShowLogin = false 
      console.log('loginMethod:',userState)
      ElMessage({
          message: res.data.msg,
          type: 'success',
          duration: 5 * 1000
      })

      getUserInfo().then(res => {
          console.log('获取用户信息：', res)
          const userData = res.data.data
          if (res.status === 200) {
              userState.email = userData.email
              userState.username = userData.username
              userState.nickname = userData.nickname
              userState.tel = userData.tel
              userState.avatar = userData.avatar
              console.log('route.name:', route.name)
              if ( route.name.includes('AIMusic') ) {
                  location.reload()
                  userState.isShowLogin = false
              }
          }
      })
  } else {
    ElMessage({
        message: res.data.msg,
        type: 'error',
        duration: 5 * 1000
    })
    // if (status == '404') {
    //   userState.pageIndex = 0 // 跳转到登录页面
    //   userState.logintabNum = 1 // 跳转到手机验证码登录
    // }
  }
  loginLoading.close()
}


</script>

<style scoped>

.el-form-item {
  margin-bottom: 30px;
}

.el-input {
  --el-input-focus-border-color: #FFF !important;
}

.login_container h3 {
  font-size: 18px;
  font-weight: 400;
}

.tabLogin {
  width: 424px;
  height: 39px;
  border: 1px solid #FFF;
  border-radius: 5px;
  margin-top: 20px;
  padding: 2px;
  box-sizing: border-box;
  
}

.tabLogin button{
  border-radius: 6px;
  width: 209px;
  height: 33px;
  color: #FFF;
  transition: all .5s;
  cursor: pointer;
  font-size: 16px;
}

.tabLogin button.active {
  background: linear-gradient(90deg, rgba(82, 240, 227, 1) 0%, rgba(243, 114, 255, 1) 100%);
}


.passLogin, .phoneLogin {
  margin-top: 30px;
}

.input_row {
  width: 424px;
  display: flex;
  flex-direction: row;
  justify-content:flex-end;
  align-items: center;
  gap: 10px;
  padding-bottom: 24px;
  position: relative;
  margin-top: 10px;
}

.err_message {
  position: absolute;
  left: 100px;
  /* color: #d03050; */
  color: #f272ff;
  bottom: 0;
}

.input_row p span {
  /* color: #d03050; */
  color: #f272ff;
  margin-right: 2px;
}

.input_con {
  width: 324px;
  height: 34px;
  border-radius: 5px;
  border: 1px solid #FFF;
  display: flex;
  flex-direction: row;
}

.input_con input {
  width: 84%;
  height: 100%;
  border: none;
  padding-left: 10px;
  background: none;
  color: #FFF;
  font-size: 14px;
  /* border-right: 1px solid #FFF; */
}

::-webkit-input-placeholder {
  color: #ddd;
}


.centered_item {
  display: flex;
  flex-direction: row;
  justify-content: center; /* 水平居中 */
}

.read_row {
  width: 100% ;
  display: flex;
  align-items: center; /* 垂直居中 */
  justify-content: center; /* 水平居中 */
  gap: 5px; /* 可调整间距 */
}

.read_row a {
  color: #7848f1;
}

.checkPass{
  width: 10%;
  cursor: pointer;
}

.checkPass img{
  width: 20px;
  height: 20px;
}

.to_pass_login {
  width: 420px;
  height: 40px;
  margin-top: 20px;
  position: relative;
}

.to_pass_login::before {
  content: '';
  width: 150px;
  height: 1px;
  background-color: #FFF;
  position: absolute;
  left: 0;
  top: 19px;
}

.to_pass_login::after {
  content: '';
  width: 150px;
  height: 1px;
  background-color: #FFF;
  position: absolute;
  right: 0;
  top: 19px;
}

.login_btn {
  width: 110px;
  height: 36px;
  background: linear-gradient(to bottom, rgba(82, 240, 227, 1) 0%, rgba(243, 114, 255, 1) 130%);
  border-radius: 5px;
  color: #FFF;
  font-size: 16px;
  display: block;
  margin: 0 auto;
  cursor: pointer;
  border: none;
}

.orther_login {
  width: 100%;
  margin-top: 10px;
}

.orther_login button {
  display: block;
  margin: 0 auto;
  color: #ccc0ed;
}

.el-checkbox:last-of-type {
  /* margin-right: 10px; */
}

.to_pass_login .el-button {
  color: #FFF;
}


.regist_findpass {
  width: 75%;
  height: 20px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  position: absolute;
  bottom: 50px;
}

.regist_findpass a {
  color: #7848f1
}

.centered_item ::v-deep(.el-form-item__error) {
  /* color: red; */
  /* color:#f272ff; */
  /* color: #53f0e3; */
  margin-left: 48px !important;
  margin-top: -8px !important;
}

.input_select {
  width: 70px;
  background: none !important;
  color: #FFF !important;
}

:deep(.el-input-group__prepend ) {
  background: none !important;
}

:deep(.el-select__wrapper) {
  background: none !important;
  border: none !important;
  box-shadow: none !important;
}

:deep(.el-input-group--prepend .el-input-group__prepend .el-select .el-select__wrapper){
  box-shadow: none !important;
  color: #FFF !important;
}

:deep(.el-select__placeholder.is-transparent) {
  color: #FFF !important;
}
:deep(.el-select__caret) {
  color: #FFF !important;
}

:deep(.el-select__placeholder) {
  color: #FFF !important;
}

:deep(.el-input__validateIcon) {
  display: none !important;
}

.el_select .el-select-dropdown__item.is-selected {
  color: #f373ff;
}


.phoneCode_con {
  padding-left: 10px;
}

.phoneCode_con button {
  width: 100%;
  height: 36px;
  border-radius: 5px;
  background-color: rgba(255,255,255,.5);
  color: #FFF;
  border:1px solid #FFF;
  box-sizing: border-box;
}


input:-webkit-autofill {
  background-color: transparent !important;
color: #FFF !important;
box-shadow: 0 0 0px 1000px transparent inset !important;
-webkit-box-shadow: 0 0 0px 1000px transparent inset !important;
}

input:-internal-autofill-previewed,
input:-internal-autofill-selected {
  -webkit-text-fill-color: #FFF;
  transition: background-color 1000s ease-out 0.5s;
}

/* 进一步保证 autofill 输入框内部的文字和背景样式 */
input:-webkit-autofill::first-line {
color: white !important;
background-color: transparent !important;
}

/* 可选: 解决浏览器中 focus 时的样式干扰 */
input:focus:-webkit-autofill {
background-color: transparent !important;
color: white !important;
}


:deep(.el-input__wrapper) {
    height: 32px !important;
    background-color: transparent !important;
    border: none;
    box-shadow: 0 0 0 1px #FFF !important;
}

:deep(.el-input__inner) {
color: #FFF;
font-size: 14px !important;
  box-shadow: 0 0 0 1000px transparent inset;
}

:deep(.el-form-item__label) {
  font-size: 14px !important;
  line-height: 36px  !important;
}




.phoneBind {
  width: 424px;
  height: 39px;
  border: 1px solid #FFF;
  border-radius: 5px;
  margin-top: 20px;
  box-sizing: border-box;
  font-size: 16px;
  line-height: 39px;
  text-align: center;
}



</style>

